package com.java.jdbc;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtils {
    public static final String URL = "jdbc:mysql://localhost:3306/testdb?serverTimezone=GMT&characterEncoding=UTF-8&Unicode=true&useSSL=false";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "123456";
    public static int executeUpdate(String sql,Object... params){

        try(Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD)){
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
            //执行命令
            int rows = preparedStatement.executeUpdate();
            return rows;
        }catch (SQLException ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    public static <T> List<T> executeQuery(Class clazz, String sql, Object... params){
        try(Connection connection = DriverManager.getConnection(URL,USERNAME,PASSWORD)){
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i+1,params[i]);
            }
            //执行查询获得ResultSet
            ResultSet rs = preparedStatement.executeQuery();
            //创建List集合
            List<T> list = new ArrayList<>();
            //遍历结果集
            while(rs.next()){
                //使用反射机制创建对象
                Object object = clazz.newInstance();
                //给对象的所有属性赋值
                //使用反射获得对象中所有属性
                Field[] fields = clazz.getDeclaredFields();
                for (Field field : fields) {
                    Object values = rs.getObject(field.getName());
                    //设置属性可以访问
                    field.setAccessible(true);
                    //给属性赋值 对象.属性 = 值
                    field.set(object,values);
                }
                //添加到集合
                list.add((T)object);
            }
        }catch (SQLException ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
